package com.dap.cms.governance.controller;

import com.dap.cms.governance.constant.ExcutorConstant;
import com.dap.cms.governance.po.CmsUserPo;
import com.dap.cms.governance.service.CmsUserService;
import com.dap.cms.governance.util.BeanValidator;
import com.dap.cms.governance.vo.UserInfoVo;
import com.dap.dao.model.Order;
import com.dap.dao.model.QueryResult;
import com.fesine.commons.entity.Result;
import com.fesine.commons.enums.ResultEnum;
import com.fesine.commons.util.ResultUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: t_cms_user表对应的控制层类
 * @author: Fesine
 * @createTime:2018/08/20
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2018/08/20
 */
@RestController
@RequestMapping("/v1")
public class CmsUserController {
    private static final Logger logger = LoggerFactory.getLogger(CmsUserController.class);
    @Autowired
    private CmsUserService cmsUserService;

    /**
     * 公司系统负责人添加CmsUserPo
     *
     * @param cmsUserPo
     * @return result
     */
    @PostMapping("/user")
    public Result addCmsUser(CmsUserPo cmsUserPo, @RequestParam(value = "componentIds", required = false) String componentIds) {
        BeanValidator.check(cmsUserPo);
        //查看用户名是否重复
        if (!cmsUserService.checkName(cmsUserPo.getName())) {
            return ResultUtils.error(500, "用户名已被占用，请重新输入用户名");
        }
        try {
            if (cmsUserPo.getUserFlag() == 2) {
                //负责人直接保存
                cmsUserService.addCmsUserPo(cmsUserPo);
            } else {
                //组件接入人员管理组件后保存
                cmsUserService.addCmsUserPoAndComponent(cmsUserPo, componentIds);
            }
            return ResultUtils.success(ResultEnum.CREATED, null);
        } catch (Exception e) {
            logger.error("新增失败", e);
            return ResultUtils.error(500, "新增失败");
        }
    }

    /**
     * 更新CmsUserPo
     *
     * @param cmsUserPo
     * @return result
     */
    @PutMapping("/user")
    public Result updateCmsUser(CmsUserPo cmsUserPo, @RequestParam(value = "componentIds", required = false)
            String componentIds, @RequestParam String oldUserName) {
        BeanValidator.check(cmsUserPo);
        if (null == cmsUserPo.getId()) {
            return ResultUtils.error(400, "数据请求错误");
        }
        if (ExcutorConstant.SYS_COMPONENT_MANAGER.equals(cmsUserPo.getUserFlag()) && StringUtils.isBlank(componentIds)) {
            return ResultUtils.error(400, "您还没有选择组件！");
        }
        try {
            cmsUserService.updateUser(cmsUserPo, componentIds, oldUserName);
            return ResultUtils.success(ResultEnum.CREATED, null);
        } catch (Exception e) {
            return ResultUtils.error(500, "用户修改失败");
        }
    }

    /**
     * 删除CmsUserPo
     *
     * @param id
     * @return result
     */
    @DeleteMapping("/user/{id}")
    public Result deleteCmsUser(@PathVariable("id") Integer id) {
        CmsUserPo cmsUserPo = new CmsUserPo();
        cmsUserPo.setId(id);
        cmsUserPo = cmsUserService.get(cmsUserPo);
        if (null != cmsUserPo) {
            cmsUserService.deleteUser(cmsUserPo);
        }
        return ResultUtils.success(ResultEnum.DELETED, null);
    }

    /**
     * 查看CmsUserPo详情
     *
     * @param id
     * @return result
     */
    @GetMapping("/user/{id}")
    public Result getCmsUser(@PathVariable("id") Integer id) {
        CmsUserPo cmsUserPo = new CmsUserPo();
        cmsUserPo.setId(id);
        cmsUserPo = cmsUserService.get(cmsUserPo);
        return ResultUtils.success(cmsUserPo);
    }

    /**
     * 查询CmsUserPo列表
     *
     * @param cmsUserPo
     * @return result
     */
    @GetMapping("/users")
    public Result listAll(CmsUserPo cmsUserPo) {
        cmsUserPo.addOrder(Order.asc("id"));
        List<CmsUserPo> list = cmsUserService.listAll(cmsUserPo);
        return ResultUtils.success(list);
    }

    /**
     * 通过公司id查询CmsUserPo列表
     *
     * @return result
     */
    @GetMapping("/users/{companyId}")
    public Result listAllByCompanyId(@PathVariable("companyId") Integer companyId) {
        CmsUserPo cmsUserPo = new CmsUserPo();
        cmsUserPo.setCompanyId(companyId);
        cmsUserPo.addOrder(Order.asc("id"));
        List<CmsUserPo> list = cmsUserService.listAll(cmsUserPo);
        return ResultUtils.success(list);
    }

    /**
     * 分页查询CmsUserPo列表
     *
     * @param cmsUserPo
     * @param pageIndex
     * @param pageSize
     * @return result
     */
    @GetMapping("/users/page")
    public Result listPage(CmsUserPo cmsUserPo, @RequestParam(value = "pageIndex",
            required = false, defaultValue = "1")
            Integer pageIndex, @RequestParam(value = "pageSize", required = false, defaultValue =
            "10") Integer pageSize) {
        cmsUserPo.addOrder(Order.asc("id"));
        QueryResult<CmsUserPo> result = cmsUserService.listPage(cmsUserPo, pageIndex, pageSize);

        long total = result.getTotalrecord();
        Map<String, Object> map = new HashMap(16);
        if (total > 0) {
            map.put("totalRecord", total);
            map.put("resultList", result.getResultlist());
        }
        return ResultUtils.success(map);
    }

    /**
     * 分页关联查询组件使用详情（含多条件模糊查询）
     *
     * @return result
     */
    @GetMapping("/userInfos/page")
    public Result listUserInfos(UserInfoVo userInfoVo, @RequestParam(value = "pageIndex",
            required = false, defaultValue = "1")
            Integer pageIndex, @RequestParam(value = "pageSize", required = false, defaultValue =
            "10") Integer pageSize) {
        //增加模糊查询条件
        //根据用户名
        if (StringUtils.isNotEmpty(userInfoVo.getName())) {
            userInfoVo.setName("%".concat(userInfoVo.getName())
                    .concat("%"));
        } else {
            userInfoVo.setName(null);
        }
        //根据组件名
        if (StringUtils.isNotEmpty(userInfoVo.getComponentNames())) {
            userInfoVo.setComponentNames("%".concat(userInfoVo.getComponentNames())
                    .concat("%"));
        } else {
            userInfoVo.setComponentNames(null);
        }
        //根据公司名
        if (StringUtils.isNotEmpty(userInfoVo.getCompanyName())) {
            userInfoVo.setCompanyName("%".concat(userInfoVo.getCompanyName())
                    .concat("%"));
        } else {
            userInfoVo.setCompanyName(null);
        }
        //根据系统名
        if (StringUtils.isNotEmpty(userInfoVo.getSysName())) {
            userInfoVo.setSysName("%".concat(userInfoVo.getSysName())
                    .concat("%"));
        } else {
            userInfoVo.setSysName(null);
        }
        QueryResult<UserInfoVo> result = cmsUserService.listUserInfo(userInfoVo, pageIndex, pageSize);
        long total = result.getTotalrecord();
        Map<String, Object> map = new HashMap(16);
        if (total > 0) {
            map.put("totalRecord", total);
            map.put("resultList", result.getResultlist());
        }
        return ResultUtils.success(map);
    }


}

